﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SQL
{
    public class IO
    {

        /// <summary>
        /// 日志是否打印
        /// </summary>
        /// <param name="str"></param>
        public static void WriteLog(string str)
        {
            try
            {
                str = "--*" + GetCallerName(2) + "()" + System.Environment.NewLine + str;
                string path = GetFilePath();
                str = "--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + System.Environment.NewLine + str + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine;
                File.AppendAllText(path, str);
            }
            catch
            {
            }
        }

        public static void WriteLog(string str, bool WriteLog)
        {
            try
            {
                if (WriteLog)
                {
                    str = "--*" + GetCallerName(2) + "()" + System.Environment.NewLine + str;

                    string path = GetFilePath();
                    str = "--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + System.Environment.NewLine + str + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine;
                    File.AppendAllText(path, str);
                }
            }
            catch
            {
            }
        }

        public static String GetCallerName(int position)
        {
            String str_callerName;

            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
            System.Diagnostics.StackFrame[] sfArr = st.GetFrames();

            System.Diagnostics.StackFrame sf = sfArr[position];
            MethodBase mb = sf.GetMethod();
            str_callerName = mb.DeclaringType.FullName + '.' + mb.Name;
            //Utility.WriteLog( // for test .
            //    "\r\n0=" + sfArr[0].GetMethod().DeclaringType.FullName + "." + sfArr[0].GetMethod().Name +
            //    "\r\n1=" + sfArr[1].GetMethod().DeclaringType.FullName + "." + sfArr[1].GetMethod().Name +
            //    "\r\n2=" + sfArr[2].GetMethod().DeclaringType.FullName + "." + sfArr[2].GetMethod().Name +
            //    "\r\n3=" + sfArr[3].GetMethod().DeclaringType.FullName + "." + sfArr[3].GetMethod().Name +
            //    "\r\nsfArr.Length=" + sfArr.Length
            //    );

            return str_callerName;
        }

        public static String GetFilePath()
        {
            String str_filePath = "";

            try
            {
                str_filePath = AppDomain.CurrentDomain.BaseDirectory + "log.txt";

                FileInfo fi = new FileInfo(str_filePath);
                if (fi.Exists && fi.Length > 1048576) // 1MB(1048576 = 1024 * 1024)  1024000
                {
                    String str_backupFilePath = AppDomain.CurrentDomain.BaseDirectory + "log_backup.txt";

                    if (File.Exists(str_backupFilePath))
                    {
                        File.Delete(str_backupFilePath);
                    }
                    File.Move(str_filePath, str_backupFilePath);
                }
            }
            catch
            {
            }

            return str_filePath;
        }

        /// <summary>
        /// 写程序运行日志
        /// </summary>
        /// <param name="str">日志内容</param>
        /// <param name="WriteLog">是否打印日志</param>
        /// <param name="FileSize">日志文件大小</param>
        public static void Log(string str, bool WriteLog, int FileSize)
        {
            try
            {
                if (WriteLog)
                {
                    str = "--*" + GetCallerName(2) + "()" + System.Environment.NewLine + str;
                    string path = GetFilePath("Log", FileSize);
                    str = "--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + System.Environment.NewLine + str + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine;
                    File.AppendAllText(path, str);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="str">错误内容</param>
        /// <param name="FileSize">日志文件大小</param>
        public static void LogError(string str, int FileSize)
        {
            try
            {
                    str = "--*" + GetCallerName(2) + "()" + System.Environment.NewLine + str;
                    string path = GetFilePath("Log_e", FileSize);
                    str = "--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + System.Environment.NewLine + str + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine;
                    File.AppendAllText(path, str);
            }
            catch
            {
            }
        }


        public static String GetFilePath(string FileName, int FileSize)
        {
            String str_filePath = "";

            try
            {
                str_filePath = AppDomain.CurrentDomain.BaseDirectory + FileName + ".txt";

                FileInfo fi = new FileInfo(str_filePath);
                if (fi.Exists && fi.Length > FileSize) // 1MB(1048576 = 1024 * 1024)  1024000
                {
                    String str_backupFilePath = AppDomain.CurrentDomain.BaseDirectory + FileName + "_backup.txt";

                    if (File.Exists(str_backupFilePath))
                    {
                        File.Delete(str_backupFilePath);
                    }
                    File.Move(str_filePath, str_backupFilePath);
                }
            }
            catch
            {
            }

            return str_filePath;
        }

        public static bool AppendTextFile(string strFilePath, string strData, Encoding encoding)
        {
            return AppendTextFile(strFilePath, strData, encoding, 0);
        }

        public static bool AppendTextFile(string strFilePath, string strData, Encoding encoding, int intFileSize)
        {
            try
            {
                ClearFileReadonlyAttribute(strFilePath);
                string directoryName = Path.GetDirectoryName(strFilePath);
                string extension = Path.GetExtension(strFilePath);
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(strFilePath);
                string str4 = fileNameWithoutExtension;
                CheckFolder(directoryName, true);
                directoryName = directoryName + @"\";
                if (intFileSize > 0)
                {
                    int num = 1;
                    str4 = fileNameWithoutExtension + "_" + num.ToString();
                    while (File.Exists(directoryName + str4 + extension))
                    {
                        FileInfo info = new FileInfo(directoryName + str4 + extension);
                        if (info.Length <= (intFileSize * 0x400))
                        {
                            break;
                        }
                        num++;
                        str4 = fileNameWithoutExtension + "_" + num.ToString();
                    }
                }
                using (FileStream stream = new FileStream(directoryName + str4 + extension, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 0x1000, false))
                {
                    lock (stream)
                    {
                        stream.Write(encoding.GetBytes(strData), 0, encoding.GetByteCount(strData));
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return true;
        }

        public static bool CheckFolder(string strFolderPath, bool CreateIfNotExist)
        {
            if (Directory.Exists(strFolderPath))
            {
                return true;
            }
            if (CreateIfNotExist)
            {
                Directory.CreateDirectory(strFolderPath);
                return true;
            }
            return false;
        }

        public static bool CheckSavePath(string strFilePath, bool CreateFolder, bool DeleteExistFile)
        {
            int num = strFilePath.LastIndexOf("/");
            int num2 = strFilePath.LastIndexOf(@"\");
            int length = (num > num2) ? num : num2;
            bool flag = CheckFolder(strFilePath.Substring(0, length), CreateFolder);
            if (DeleteExistFile)
            {
                if (!File.Exists(strFilePath))
                {
                    return flag;
                }
                try
                {
                    ClearFileReadonlyAttribute(strFilePath);
                    File.Delete(strFilePath);
                }
                catch
                {
                }
            }
            return flag;
        }

        public static void ClearFileReadonlyAttribute(string strFilePath)
        {
            if (File.Exists(strFilePath))
            {
                try
                {
                    File.SetAttributes(strFilePath, FileAttributes.Normal);
                }
                catch
                {
                }
            }
        }

        public static long GetFileSize(string strFilePath)
        {
            try
            {
                FileInfo info = new FileInfo(strFilePath);
                return info.Length;
            }
            catch
            {
                return 0L;
            }
        }

        public static string GetFileSizeString(long lngFileSize)
        {
            double num = ((double)lngFileSize) / 1024.0;
            if (num < 1000.0)
            {
                return (num.ToString("#0.00") + " KB");
            }
            double num2 = ((double)lngFileSize) / 1048576.0;
            if (num2 < 1000.0)
            {
                return (num2.ToString("#0.00") + " MB");
            }
            double num3 = ((double)lngFileSize) / 1073741824.0;
            return (num3.ToString("#0.00") + " GB");
        }

        public static byte[] ReadBinaryFile(string strFilePath)
        {
            FileStream input = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader reader = new BinaryReader(input);
            byte[] buffer = reader.ReadBytes((int)reader.BaseStream.Length);
            reader.Close();
            input.Close();
            return buffer;
        }

        public static string ReadTextFile(string strFilePath)
        {
            string str2;
            try
            {
                using (FileStream stream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    lock (stream)
                    {
                        StreamReader reader = new StreamReader(stream, Encoding.Default);
                        string str = reader.ReadToEnd();
                        reader.Close();
                        reader.Dispose();
                        str2 = str;
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return str2;
        }

        public static bool WriteBinaryFile(string strFilePath, byte[] byteArray)
        {
            try
            {
                ClearFileReadonlyAttribute(strFilePath);
                FileStream output = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
                BinaryWriter writer = new BinaryWriter(output);
                writer.Write(byteArray);
                writer.Close();
                output.Close();
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return true;
        }

        public static string WriteRndFile(string strExtend, string strData)
        {
            string environmentVariable;
            try
            {
                environmentVariable = Environment.GetEnvironmentVariable("Temp");
            }
            catch
            {
                environmentVariable = Environment.CurrentDirectory;
                if (!Directory.Exists(environmentVariable + @"\Temp"))
                {
                    Directory.CreateDirectory(environmentVariable + @"\Temp");
                }
                environmentVariable = environmentVariable + @"\Temp";
            }
            return WriteRndFile(environmentVariable, strExtend, strData);
        }

        public static string WriteRndFile(string strFolderName, string strExtend, string strData)
        {
            return WriteRndFile(strFolderName, "_BYS", strExtend, strData);
        }

        public static string WriteRndFile(string strFolderName, string strPrefix, string strExtend, string strData)
        {
            string str2;
            try
            {
                Random random = new Random();
                string path = (strFolderName + @"\" + strPrefix) + random.Next(1, 0x186a0).ToString() + "." + strExtend;
                StreamWriter writer = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
                writer.Write(strData);
                writer.Close();
                str2 = path;
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return str2;
        }

        public static bool WriteTextFile(string strFilePath, string strData)
        {
            return WriteTextFile(strFilePath, strData, Encoding.GetEncoding("gb2312"));
        }

        public static bool WriteTextFile(string strFilePath, string strData, Encoding encoding)
        {
            try
            {
                ClearFileReadonlyAttribute(strFilePath);
                CheckFolder(Path.GetDirectoryName(strFilePath), true);
                using (FileStream stream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 0x1000, false))
                {
                    lock (stream)
                    {
                        stream.Write(encoding.GetBytes(strData), 0, encoding.GetByteCount(strData));
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return true;
        }


    }
}
